package com.xue.service.sys;

import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xue.common.core.IBaseDAO;
import com.xue.dao.sys.SysMenuDAO;
import com.xue.pojo.sys.SysMenu;

//2018-12-28 15:14:49
@Service("SysMenuService")
public class SysMenuService implements ISysMenuService {
	@Autowired
	private SysMenuDAO dao;

	// 从id查找
	private static final Map<String, SysMenu> MENU_ID_MAP = new HashMap<>();
	// 从url查找
	private static final Map<String, SysMenu> MENU_LINK_MAP = new HashMap<>();

	public static Optional<String> getMenuByLink(String link) {
		return Optional.ofNullable(MENU_LINK_MAP.get(link)).map(m -> m.getId());
	}

	@PostConstruct
	public void initSysMenu() {
		String sysVersion = "0";
		Map<String, Object> ps = new HashMap<>();
		ps.put("sysVersion", sysVersion);
		List<SysMenu> menus = dao.queryAll(ps);
		// 构建以id 为key 的map,并缓存
		// MENU_ID_MAP = menus.stream().collect(Collectors.toMap(SysMenu::getId,
		// Function.identity()));
		for (SysMenu m : menus) {
			MENU_ID_MAP.put(m.getId(), m);
			if (null != m.getLink() && !"".equals(m.getLink().trim())) {
				MENU_LINK_MAP.put(m.getLink(), m);
			}
		}
		// buildTree(menus);
	}

	// 利用菜单构建树
	private List<SysMenu> buildMenuTree(List<SysMenu> menus, boolean isFilter) {
		boolean DEBUG = false;
		List<SysMenu> level1 = menus;
		if (isFilter) {
			// 第一级菜单pid=0 并排序
			level1 = menus.stream().filter(m -> "00".equals(m.getPid()))
					.sorted(Comparator.comparing(SysMenu::getOrderNo)).collect(Collectors.toList());
		}
		// 以父id查找子菜单列表
		// TreeMap<String, List<Matchs>> matchsListMap = matchsList.stream()
		// .collect(Collectors.groupingBy(Matchs::getMatchDate,TreeMap::new,Collectors.toList()));

		Map<String, List<SysMenu>> subMenuMap = menus.stream().collect(Collectors.groupingBy(SysMenu::getPid));

		// 遍历第一级菜单
		for (SysMenu m1 : level1) {
			// 遍历第二级菜单
			List<SysMenu> level2 = subMenuMap.get(m1.getId());
			if (null != level2) {
				level2 = level2.stream().sorted(Comparator.comparing(SysMenu::getOrderNo)).collect(Collectors.toList());
				m1.setChildren(level2);

				// 遍历第三级菜单
				for (SysMenu m2 : level2) {
					List<SysMenu> level3 = subMenuMap.get(m2.getId());
					if (null != level3) {
						level3 = level3.stream().sorted(Comparator.comparing(SysMenu::getOrderNo))
								.collect(Collectors.toList());
						m2.setChildren(level3);

					}
				}
			}
		}

		if (DEBUG) {
			level1.forEach(m -> System.out.println(m));
		}

		return level1;
	}

	// 从菜单id构建树
	// isNavigateMenu 是否导航菜单
	@Override
	public List<SysMenu> buildMenuTree(Set<String> menuIds, String... resourceType) {
		return buildMenuTreeInternal(menuIds, true, resourceType);
	}

	@Override
	public List<SysMenu> buildMenuTreeNoFilter(Set<String> menuIds, String... resourceType) {
		return buildMenuTreeInternal(menuIds, false, resourceType);
	}

	private List<SysMenu> buildMenuTreeInternal(Set<String> menuIds, boolean isFilter, String... resourceType) {
		Set<String> resourceTypeSet = new HashSet<>();
		for (String rt : resourceType) {
			resourceTypeSet.add(rt);
		}
		final boolean hasFilter = !resourceTypeSet.isEmpty();
		List<SysMenu> menus = menuIds.stream().map(id -> MENU_ID_MAP.get(id))
				.filter(m -> hasFilter ? resourceTypeSet.contains(m.getResourceType()) : true)
				.collect(Collectors.toList());
		return buildMenuTree(menus, isFilter);
	}

	@Override
	public Set<String> queryMenuIdsByUserId(String userId, Integer sysVersion) {
		return dao.queryMenuIdsByUserId(userId, sysVersion.intValue());
	}

	@Override
	public List<String> loadUserShouCangMenuIds(Map<String, Object> params) {
		return dao.loadUserShouCangMenuIds(params);
	}

	@Override
	public void deleteUserShouCang(Map<String, Object> params) {
		dao.deleteUserShouCang(params);
	}

	@Override
	public int checkUserMenuId(Map<String, Object> params) {
		return dao.checkUserMenuId(params);
	}

	@Override
	public void saveUserShouCang(Map<String, Object> params) {
		dao.saveUserShouCang(params);
	}

	@Override
	public List<String> loadUserShouCangMenuCodes(Map<String, Object> params) {
		return dao.loadUserShouCangMenuCodes(params);
	}

	@Override
	public List<SysMenu> queryParent(Map<String, Object> params) {
		return dao.queryParent(params);
	}

	@Override
	public List<SysMenu> querySub(Map<String, Object> params) {
		return dao.querySub(params);
	}

	/**
	 * 
	 * TODO 查询通用角色对应的菜单ids
	 * 
	 * @see com.app.service.sys.ISysMenuService#queryMenuIdsByCommonRole(java.lang.Integer)
	 */
	@Override
	public Set<String> queryMenuIdsByCommonRole(Integer sysVersion) {
		// TODO Auto-generated method stub
		return dao.queryMenuIdsByCommonRole(sysVersion.intValue());
	}

	@Override
	public IBaseDAO<SysMenu, String> getDao() {
		return dao;
	}

	

	
}
